import { downLoadPackage, getPackageStep } from '@/api/scene';
import { useRequest } from '@jl/common/composable';
import { messageUtil } from '@jl/element-plus/utils';

const { run: downLoadPackageRun, data: downLoadPackageDate } = useRequest<
  any,
  API.Scene.Scene | null
>(downLoadPackage, null);

/**
 *
 * @param 加载资源包
 *
 */
export const loadingResources = async (item: any, type?: string, callback?: any) => {
  let { activityId, configJson, activityName, conifgId, projectId } = item;

  if (!configJson) return;

  let srcReg = /\/res\/[^"]*/g;
  let resoList = configJson.match(srcReg) || [];
  let resoString = resoList.join(';');
  await downLoadPackageRun({
    activityId,
    resoList: resoString,
    actName: activityName,
    actConfigId: conifgId,
    projectId: projectId,
    appType: type == '二次开发' ? 'redev' : 'offline',
  });
  callback && callback(downLoadPackageDate.value?.transId);
  // if (isDown) {
  //   messageUtil.warning(`正在生成${type}包，请到【下载管理】里面查看`);
  // }
  if (downLoadPackageDate.value?.transId) {
    let timer = setInterval(async () => {
      try {
        const result = await getPackageStep({
          params: { transId: downLoadPackageDate.value?.transId },
        });
        const failStatusList = [33, 36, 39];
        //31 收集中 32 收集完成 33 收集失败 34 打包中 35 打包完成 36 打包失败 37 传输中 38 传输完成 39 传输失败 40 导出完成
        if (result.stateCode == 40) {
          clearInterval(timer);
          const linkUrl = `${process.env.VUE_APP_PROXY_BASE_URL}/${downLoadPackageDate.value.downloadLink}`;
        } else if (failStatusList.includes(result.stateCode)) {
          messageUtil.warning(result.stateDesp);
          clearInterval(timer);
        }
      } catch (error) {
        clearInterval(timer);
      }
    }, 1000);
  }
};
